﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleChart.Kernel.Series;
using System.Data;

namespace SimpleChart.Kernel.Painter
{
    class LineSeriesPainter : SeriesPainterBase
    {
        public override void Draw(Graphics graphics, Chart chart, SeriesBase series, int width, int height)
        {
            LineSeries lineSeries = series as LineSeries;

            decimal ceiling = ChartHelper.GetAxisYCeiling(chart.Data, chart.SeriesCollection, series.AxisType);

            List<PointF> points = ChartHelper.GetPoints(chart.Data, 0f, (float)ceiling, series.AxisYMember, width, height);

            Pen pen = new Pen(series.Color);
            pen.Width = 3;
            graphics.DrawLines(pen, points.ToArray());

            if (lineSeries.ShowCirclePoint)
            {
                DrawCirclePoint(graphics, points, lineSeries.CirclePointColor);
            }

            if (series.ShowValueLabel)
            {
                DrawValeLabels(graphics, points, lineSeries.Color, chart.Data, series.AxisYMember);
            }
        }

        private void DrawValeLabels(Graphics graphics, List<PointF> points, Color valueLabelColor, DataTable data, string axisYMember)
        {
            Brush brush = new SolidBrush(valueLabelColor);
            string fontName = SystemFonts.DefaultFont.FontFamily.Name;
            Font font = new Font(fontName, 12, FontStyle.Bold);

            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Center;

            for (int i = 0; i < data.Rows.Count; i++)
            {
                graphics.DrawString(data.Rows[i][axisYMember].ToString(), font, brush, new RectangleF {X = points[i].X + 5, Y = points[i].Y - 16, Width = 120, Height = 20 }, format);
            }
        }

        private void DrawCirclePoint(Graphics graphics, List<PointF> points, Color circlePointColor)
        {
            foreach (var point in points)
            {
                graphics.FillEllipse(new SolidBrush(circlePointColor), new RectangleF() { X = point.X - 4, Y = point.Y - 4, Width = 8, Height = 8 });
            }
        }
    }
}
